package cn.nbs.category.dao;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanListHandler;

import cn.com.hkr.jdbc.TxQueryRunner;
import cn.nbs.category.entity.Category;

public class CategoryDao {
	private TxQueryRunner qr = new TxQueryRunner();

	
	/**
	 * 查询所有分类
	 * @return
	 */
	public List<Category> findAll() {
		//查询所有一级分类
		String sql = "select * from t_category where pid is null order by orderBy";
		List<Category> parentList = null;
		try {
			parentList = qr.query(sql, new BeanListHandler<Category>(Category.class));
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		
		//遍历一级分类，将一级分类下的二级分类封装到父分类里
		for (Category parent : parentList) {
			List<Category> children = findByParent(parent);
			parent.setChildren(children);
		}
		
		//返回父分类集合
		
		return parentList;
	}
	
	/**
	 * 通过父分类查询子分类集合
	 * @param parent
	 * @return
	 */
	public List<Category>  findByParent(Category parent){
		String sql = "select cid,cname,`desc` from t_category where pid=?  order by orderBy";
		try {
			return qr.query(sql, new BeanListHandler<Category>(Category.class),parent.getCid());
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}
	
	
	
	
	
}
